<?php

namespace app\controllers;

use app\models\Class2;
use app\models\DataRelationship;
use app\models\Notebook;
use app\models\SpeakContent;
use app\models\SpeakPerson;
use yii\helpers\Url;
use \yii\web\Controller;
class SpeakingController extends Controller
{
    public $layout = 'speaking';
    public function beforeAction($action)
    {
        $session = \Yii::$app->session;
        $session->open();
        if (!isset($session['user_id'])) {
            if(isset($_COOKIE['dianke_user_id']))
                $this->redirect('?r=site/dologin&islogin='.$_COOKIE['dianke_user_id']);
            else
                $this->redirect('?r=site/login');
        }
        return parent::beforeAction($action);
    }
    public function actionIndex()
    {
        $session = \Yii::$app->session;
        $session->open();
        $session['review_class1_name']='speaking';
        $action = 'index';
        $session['user_id_speak_person_type1']=SpeakPerson::find()->where(['uid'=>$session['user_id'],'speak_content_id'=>$session['speak_id']])->one();
        $session['speak_userid_id_type1']=$session['user_id_speak_person_type1']['id'];
        $request = \Yii::$app->request;
        if($request->isAjax)
        {
            $note=$request->post('saved-note');
            $my_note=$session['speak_note'];
            $my_note->note=$note;
            $my_note->save();
            $session['speak_note']=$my_note;
        }
        elseif ($request->isPost) {
            $page = $request->post('page');
            $practice = $request->post('waytopra');
            $speak_content = $session['speak_content'];
            $class2_id=Class2::find()->where(['id'=>$speak_content['class2_id']])->one();
            $session['speak_class02_id']=$class2_id;
            $my_note=$session['speak_note'];
            if(!isset($session['user_id_speak_person_type1'])) {
                if ($session['form'] == 4&&$speak_content['type'] == 3) {
                    $total_views4 = $request->post('total-views1');
                    $first_view4 = $request->post('first-view1');
                    $second_view4 = $request->post('second-view1');
                    $session['total_views4'] = $total_views4;
                    $session['first_view4'] = $first_view4;
                    $session['second_view4'] = $second_view4;
                    $session['form'] = 0;
                } else if ($session['form'] == 5&&$speak_content['type'] == 3) {
                    $total_views5 = $request->post('total-views1');
                    $first_view5 = $request->post('first-view1');
                    $second_view5 = $request->post('second-view1');
                    $session['total_views5'] = $total_views5;
                    $session['first_view5'] = $first_view5;
                    $session['second_view5'] = $second_view5;;
                    $session['form'] = 0;
                } else if ($session['form'] == 3&&$speak_content['type'] == 3) {
                    $speak_person = new SpeakPerson();
                    $speak_person->readtheme = $session["total_views4"];
                    $speak_person->readhand1 = $session["first_view4"];
                    $speak_person->readhand2 = $session["second_view4"];
                    $speak_person->listentheme = $session["total_views5"];
                    $speak_person->listenhand1 = $session["first_view5"];
                    $speak_person->listenhand2 = $session["second_view5"];
                    $speak_person->uid = $session['user_id'];
                    $speak_person->speak_content_id = $session['speak_id'];
                    $now=time();
                    $speak_person->time = $now-$session['begin_time'];
                    $data = $speak_person->save();
                    $session['speak_person_id'] = $speak_person->attributes['id'];
                    $session['form'] = 0;
                }else if ($session['form'] == 2&&$speak_content['type'] == 2) {
                    $speak_person = new SpeakPerson();
                    $speak_person->readtheme = 'null';
                    $speak_person->readhand1 = 'null';
                    $speak_person->readhand2 = 'null';
                    $speak_person->listentheme = 'null';
                    $speak_person->listenhand1 = 'null';
                    $speak_person->listenhand2 = 'null';
                    $speak_person->uid = $session['user_id'];
                    $speak_person->speak_content_id = $session['speak_id'];
                    $now=time();
                    $speak_person->time = $now-$session['begin_time'];
                    $data = $speak_person->save();
                    $session['speak_person_id'] = $speak_person->attributes['id'];
                    $session['form'] = 0;
                }else if ($session['form'] == 2&&$speak_content['type'] == 1) {
                    $speak_person = new SpeakPerson();
                    $speak_person->readtheme = 'null';
                    $speak_person->readhand1 = 'null';
                    $speak_person->readhand2 = 'null';
                    $speak_person->listentheme = 'null';
                    $speak_person->listenhand1 = 'null';
                    $speak_person->listenhand2 = 'null';
                    $speak_person->uid = $session['user_id'];
                    $speak_person->speak_content_id = $session['speak_id'];
                    $now=time();
                    $speak_person->time = $now-$session['begin_time'];
                    $data = $speak_person->save();
                    $session['speak_person_id'] = $speak_person->attributes['id'];
                    $session['form'] = 0;
                }
            }
            elseif(isset($session['user_id_speak_person_type1'])) {
                if ($session['form'] == 4&&$speak_content['type'] == 3) {
                    $total_views4 = $request->post('total-views1');
                    $first_view4 = $request->post('first-view1');
                    $second_view4 = $request->post('second-view1');
                    $session['total_views4'] = $total_views4;
                    $session['first_view4'] = $first_view4;
                    $session['second_view4'] = $second_view4;
                    $session['form'] = 0;
                } else if ($session['form'] == 5&&$speak_content['type'] == 3) {
                    $total_views5 = $request->post('total-views1');
                    $first_view5 = $request->post('first-view1');
                    $second_view5 = $request->post('second-view1');
                    $session['total_views5'] = $total_views5;
                    $session['first_view5'] = $first_view5;
                    $session['second_view5'] = $second_view5;
                    $session['form'] = 0;
                } else if ($session['form'] == 3&&$speak_content['type'] == 3) {
                    $speak_person =SpeakPerson::findOne($session['speak_userid_id_type1']);
                    $speak_person->readtheme = $session["total_views4"];
                    $speak_person->readhand1 = $session["first_view4"];
                    $speak_person->readhand2 = $session["second_view4"];
                    $speak_person->listentheme = $session["total_views5"];
                    $speak_person->listenhand1 = $session["first_view5"];
                    $speak_person->listenhand2 = $session["second_view5"];
                    $speak_person->uid = $session['user_id'];
                    $speak_person->speak_content_id = $session['speak_id'];
                    $now=time();
                    $speak_person->time = $now-$session['begin_time'];
                    $data = $speak_person->save();
                    $session['write_person_id'] = $speak_person->attributes['id'];
                    $session['form'] = 0;
                }
                else if($session['form'] == 2&&$speak_content['type'] == 2){
                    $speak_person =SpeakPerson::findOne($session['speak_userid_id_type1']);
                    $speak_person->readtheme = 'null';
                    $speak_person->readhand1 = 'null';
                    $speak_person->readhand2 = 'null';
                    $speak_person->listentheme = 'null';
                    $speak_person->listenhand1 = 'null';
                    $speak_person->listenhand2 = 'null';
                    $speak_person->uid = $session['user_id'];
                    $speak_person->speak_content_id = $session['speak_id'];
                    $now=time();
                    $speak_person->time = $now-$session['begin_time'];
                    $data = $speak_person->save();
                    $session['write_person_id'] = $speak_person->attributes['id'];
                    $session['form'] = 0;
                }
                else if($session['form'] == 2&&$speak_content['type'] == 1){
                    $speak_person =SpeakPerson::findOne($session['speak_userid_id_type1']);
                    $speak_person->readtheme = 'null';
                    $speak_person->readhand1 = 'null';
                    $speak_person->readhand2 = 'null';
                    $speak_person->listentheme = 'null';
                    $speak_person->listenhand1 = 'null';
                    $speak_person->listenhand2 = 'null';
                    $speak_person->uid = $session['user_id'];
                    $speak_person->speak_content_id = $session['speak_id'];
                    $now=time();
                    $speak_person->time = $now-$session['begin_time'];
                    $data = $speak_person->save();
                    $session['write_person_id'] = $speak_person->attributes['id'];
                    $session['form'] = 0;
                }
            }
            if($page==1){
                $state='begin';
            }
            else{
                $state='next';
            }
            $result=[
                'speak_content' => $speak_content,
                'page' => $page + 1,
                'action' => $action,
                'token' => $session['time_token'],
                'state' => $state,
                'my_note'=>$my_note,
            ];
            /*unset($session['practice']);*/
            if ($speak_content['type'] == 1)
            {
                switch ($page)
                {
                    case 1:
                        return $this->render('1', $result);
                        break;
                    case 2:
                        return $this->render('3', $result);
                        break;
                    case 3:
                        return $this->render('2', $result);
                        break;
                    case 4:
                        $session['speak_complete']=true;
                        $this->saveState($speak_content);
                        $this->redirect('?r=community/speaking&id='.$speak_content['id']);
                        break;
                }
            }
            elseif ($speak_content['type'] == 2)
            {
                switch ($page)
                {
                    case 1:
                    case 2:
                        return $this->render('1', $result);
                        break;
                    case 3:
                        return $this->render('3', $result);
                        break;
                    case 4:
                        return $this->render('2', $result);
                        break;
                    case 5:
                        $session['speak_complete']=true;
                        $this->saveState($speak_content);
                        $this->redirect('?r=community/speaking&id='.$speak_content['id']);
                        break;
                }
            }
            elseif ($speak_content['type'] == 3)
            {
                if ($page == 1) {
                    if (isset($practice)) {
                        $session['practice'] = 1;
                    } else {
                        $session['practice'] = 0;
                    }
                }
                switch ($page)
                {
                    case 1:
                    case 2:
                        return $this->render('1', $result);
                        break;
                    case 3:
                        return $this->render('4', $result);
                        break;
                    case 4:
                        return $this->render('5', $result);
                        break;
                    case 5:
                        return $this->render('3', $result);
                        break;
                    case 6:
                        return $this->render('2',$result);
                        break;
                    case 7:
                        $session['speak_complete']=true;
                        $this->saveState($speak_content);
                        $this->redirect('?r=community/speaking&id='.$speak_content['id']);
                        break;
                }
            }
            else {
                echo "展示答案";
                die;
            }
        }
        else {
            $this->layout = 'direction';
            $session['speak_complete']=false;
            unset($session['speak_note']);
            $session = \Yii::$app->session;
            $session->open();
            unset($session['total_views4']);
            unset($session['first_view4']);
            unset($session['second_view4']);
            unset($session['total_views5']);
            unset($session['first_view5']);
            unset($session['second_view5']);
            $request = \Yii::$app->request;
            if ($request->get('id')) {
                $id = $request->get('id');
                $speak_content=SpeakContent::findOne($id);
                $where=[
                    'class1_id'=>$speak_content['class1_id'],
                    'class2_id'=>$speak_content['class2_id'],
                    'question_id'=>$speak_content['id'],
                    'user_id'=>$session['user_id']
                ];
                $my_note=Notebook::find()->where($where)->one();
                if(!isset($my_note))
                {
                    $my_note=new Notebook();
                    $my_note->class1_id=$speak_content['class1_id'];
                    $my_note->class2_id=$speak_content['class2_id'];
                    $my_note->question_id=$speak_content['id'];
                    $my_note->user_id=$session['user_id'];
                    $my_note->save();
                }
                $class2_name=Class2::findOne($speak_content['class2_id'])['name'];
                $session['speak_id']=$id;
                $session['speak_note']=$my_note;
                $session['speak_content']=$speak_content;
                return $this->render('direction',['action'=>$action,'page'=>1,'class2_name'=>$class2_name,'hear_number'=>$speak_content['hear_number']]);
            }
        }

    }
    public function valid_wav_file($file)
    {
        $handle = fopen($file, 'r');
        $header = fread($handle, 4);
        list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
        $format = fread($handle, 4);
        fclose($handle);
        return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
    }

    public function actionUpload()
    {
        $session = \Yii::$app->session;
        $session->open();
        if (!isset($session['user_id']))
        {
            $this->redirect('?r=site/login');
        }
        $save_folder = \Yii::$app->basePath;
        $save_folder=$save_folder."/web/audio/user_voice";
        if(! file_exists($save_folder)) {
            if(! mkdir($save_folder)) {
                die("failed to create save folder $save_folder");
            }
        }
        $user_id=$session['user_id'];
        $content_id=$session['speak_content']['id'];
        $key = 'filename';
        $tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
        $upload_name = md5("speaking_{$user_id}_{$content_id}").".wav";//$_FILES["upload_file"]["name"][$key];
        $type = $_FILES["upload_file"]["type"][$key];
        $filename = "$save_folder/$upload_name";
        if($type == 'audio/wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && $this->valid_wav_file($tmp_name)) {
            move_uploaded_file($tmp_name, $filename);
        }

    }

    private function saveState($speak_content)
    {
        $session=\Yii::$app->session;
        $session->open();
        $where=[
            'user_id'=>$session['user_id'],
            'class1_id'=>$speak_content['class1_id'],
            'class2_id'=>$speak_content['class2_id'],
            'content_id'=>$speak_content['id']
        ];
        $data_relation=DataRelationship::find()->where($where)->one();
        if(!isset($data_relation))
        {
            //新建一条数据
            $data_relation=new DataRelationship();
            $data_relation->user_id=$session['user_id'];
            $data_relation->class1_id=$speak_content['class1_id'];
            $data_relation->class2_id=$speak_content['class2_id'];
            $data_relation->content_id=$speak_content['id'];
        }
        $data_relation->last_time=date('Y-m-d H:i:s');
        $data_relation->save();

        //更新做题人数
        $where=[
            'class1_id'=>$speak_content['class1_id'],
            'class2_id'=>$speak_content['class2_id'],
            'content_id'=>$speak_content['id']
        ];
        $rows=DataRelationship::find()->select(['id'])->where($where)->asArray()->all();
        //$speak_content=SpeakContent::findOne($speak_content['id']);
        $speak_content->num=count($rows);
        $speak_content->save(false);
    }
}